package com.caijin.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.caijin.common.core.domain.Result;
import com.caijin.common.core.domain.entity.Course;
import com.caijin.common.enums.ResultCode;
import com.caijin.system.entity.StudentClazz;
import com.caijin.system.mapper.StudentClazzMapper;
import com.caijin.system.service.IClazzService;
import com.caijin.system.service.ICourseService;
import com.caijin.system.service.IStudentClazzService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 学生班级关联表 服务实现类
 * </p>
 *
 * @author Peas
 * @since 2021-01-18
 */
@Service
public class StudentClazzServiceImpl extends ServiceImpl<StudentClazzMapper, StudentClazz> implements IStudentClazzService {

    @Autowired
    private StudentClazzMapper mapper;

    @Autowired
    private IClazzService clazzService;

    @Autowired
    private ICourseService courseService;

    /**
     * 学生加入班级
     *
     * @param studentClazz 学生班级联合模型
     * @return 结果
     */
    @Override
    public Result joinClazz(StudentClazz studentClazz) {
        QueryWrapper<StudentClazz> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("sno", studentClazz.getSno());
        queryWrapper.eq("clazz_id", studentClazz.getClazzId());
        StudentClazz studentClazz1 = this.mapper.selectOne(queryWrapper);
        int insert = 0;

        if (!studentClazz.equals(studentClazz1))
            insert = this.mapper.insert(studentClazz);
        else
            return Result
                    .error()
                    .message(ResultCode.USER_ALREADY_EXISTS_IN_THE_COURSE.getMessage())
                    .code(ResultCode.USER_ALREADY_EXISTS_IN_THE_COURSE.getCode());

        return insert != 0 ? Result.ok() : Result.error();
    }

    /**
     * 通过学号获取课程列表
     *
     * @param sno 学号
     * @return 班级id列表
     */
    @Override
    public Result getCourseListBySno(Long sno) {
        List<Course> courseListBySno = mapper.getCourseListBySno(sno);
        return courseListBySno != null ? Result.ok().data("courseList", courseListBySno) : Result.error();
    }

    @Override
    public Result deleteStudent(Long sno, Long clazzId) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("sno",sno);
        queryWrapper.eq("clazz_id",clazzId);
        return mapper.delete(queryWrapper) == 0 ? Result.error() : Result.ok();
    }
}
